package net.godcode.t5c.components;

import java.text.SimpleDateFormat;
import java.util.Date;

import net.godcode.t5c.mixins.RenderNode;

import org.apache.tapestry.MarkupWriter;
import org.apache.tapestry.TapestryConstants;
import org.apache.tapestry.annotations.BeginRender;
import org.apache.tapestry.annotations.Mixin;
import org.apache.tapestry.annotations.Parameter;
import org.apache.tapestry.annotations.SetupRender;
import org.apache.tapestry.annotations.SupportsInformalParameters;
import org.apache.tapestry.corelib.mixins.DiscardBody;
import org.apache.tapestry.corelib.mixins.RenderInformals;

@SupportsInformalParameters
/**
 * DateFormat allows easy formatting and/or localization of dates.
 * 
 * @author Chris Lewis Dec 26, 2007 <chris@thegodcode.net>
 * @version $Id: DateFormat.java 85 2008-01-03 21:53:46Z burningodzilla $
 * @since 0.2.0
 */
public class DateFormat {
	
	/** The date to format. */
	@Parameter(required = true)
	private Date date;
	
	/** The format as supported by {@link SimpleDateFormat}. */
	@Parameter(defaultPrefix = TapestryConstants.LITERAL_BINDING_PREFIX)
	private String format = null;
	
	/*
	 * Hoping this ticket is addressed, as it will shorten this:
	 * https://issues.apache.org/jira/browse/TAPESTRY-2000
	 */
	
	@SuppressWarnings("unused")
	@Mixin
	private RenderInformals renderInformals;
	
	@SuppressWarnings("unused")
	@Mixin
	private DiscardBody discardBody;
	
	@SuppressWarnings("unused")
	@Mixin
	private RenderNode renderNode;
	
	private SimpleDateFormat formatter;
	private String formattedDate;
	
	@SetupRender
	void setupRender() {
		//TODO smarter constructor to support further localization
		formatter = format == null ? new SimpleDateFormat() : new SimpleDateFormat(format);
		formattedDate = formatter.format(date);
	}
	
	@BeginRender
	void beginRender(MarkupWriter writer) {
		writer.write(formattedDate);
	}
	
}